<?php
/**
 * Created by PhpStorm.
 * User: yangliqiang
 * Date: 2018/9/9
 * Time: 21:44
 */

namespace app\api\models;

use app\api\core\CreateUuid;
use app\api\core\wechat\wxAction;
use Cm;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use yii\log\EmailTarget;
use app\api\models\MaterialModel;

class MsgModel extends BaseModel
{
    /**
     * 一般群发
     */
    public  function actionSendMsg()
    {
        $type = Cm::$req->post('type', ['reg'=>'/^\w+/', 'title'=>'发送内容类型']);
        $content= Cm::$req->post('content', [ 'title'=>'发送内容']);
        $articles = Cm::$req->post('articles', ['reg' => '/[^,:{}\\[\\]0-9.\-+Eaeflnr-u \n\r\t]/', 'title' => '图文消息', 'null', 'empty']);
        $user_name= Cm::$req->post('user_name', [ 'title'=>'发送者']);
        $to_type = Cm::$req->post('to_type', ['reg'=>'/^\d+/', 'title'=>'发送对象']);
        $subscribe = Cm::$req->post('subscribe', ['title'=>'关注时间']);
        $age = (int)Cm::$req->post('age', ['reg'=>'/^\d+/', 'title'=>'年龄标签', 'null', 'empty']);
        $sex = (int)Cm::$req->post('sex', ['reg'=>'/^\d+/', 'title'=>'性别', 'null', 'empty']);
        $education = (int)Cm::$req->post('education', ['reg'=>'/^\d+/', 'title'=>'教育标签', 'null', 'empty']);
        $territory = (int)Cm::$req->post('territory', ['reg'=>'/^\d+/', 'title'=>'地域标签', 'null', 'empty']);
        $source = (int)Cm::$req->post('source', ['reg'=>'/^\d+/', 'title'=>'粉丝来源', 'null', 'empty']);
        $active_level = (int)Cm::$req->post('active_level', ['reg'=>'/^\d+/', 'title'=>'活跃度', 'null', 'empty']);
        $industry = (int)Cm::$req->post('industry', ['reg'=>'/^\d+/', 'title'=>'行业标签', 'null', 'empty']);
        $financial_consumption = (int)Cm::$req->post('financial_consumption', ['reg'=>'/^\d+/', 'title'=>'消费偏好标签', 'null', 'empty']);
        $content_style = (int)Cm::$req->post('content_style', ['reg'=>'/^\d+/', 'title'=>'内容形式偏好标签', 'null', 'empty']);
        $consumption_ability = (int)Cm::$req->post('consumption_ability', ['reg'=>'/^\d+/', 'title'=>'消费能力', 'null', 'empty']);
        $tags = Cm::$req->post('tags', ['title'=>'自定义标签', 'null', 'empty']);

        if (!in_array($type, ['text', 'news'])) {
            \Cm::$res->error('群发类型参数不正确');
        }
        if (!in_array($to_type, [1,2,3])) {
            \Cm::$res->error('发送对象参数不正确');
        }
        if (in_array($type, ['news'])) {
            if (!empty($articles)) {
                $verJson = $this->verJson($articles);
                if (!$verJson['flag']) {
                    Cm::$res->error('无效json格式: 无效参数articles');
                }
            }
        }
        if (is_numeric($subscribe)) {
            if (!in_array((int)$subscribe, [1,2,3])) {
                \Cm::$res->error('关注时间参数不正确');
            }
        } else {
            if (!preg_match('/^\d{4}-\d{2}-\d{2}\s\d{4}-\d{2}-\d{2}/', $subscribe, $arr)) {
                \Cm::$res->error('关注时间参数不正确');
            }
        }
        if (!in_array($to_type, [1,2,3])) {
            \Cm::$res->error('发送对象参数不正确');
        }

        if (!empty($age) && !in_array($age, [1,2,3,4,5,6])) {
            \Cm::$res->error('年龄标签参数不正确');
        }

        if (!empty($sex) && !in_array($sex, [1,2])) {
            \Cm::$res->error('性别参数不正确');
        }

        if (!empty($education) && !in_array($education, [1,2,3,4,5,6])) {
            \Cm::$res->error('教育标签参数不正确');
        }

        if (!empty($territory) && !in_array($territory, [1,2,3,4,5,6,7,8])) {
            \Cm::$res->error('地域标签参数不正确');
        }
        if (!empty($source) && !in_array($source, [0,1,2,3,4,5,6,7])) {
            \Cm::$res->error('粉丝来源不正确');
        }
        if (!empty($active_level) && !in_array($active_level, [1,2,3])) {
            \Cm::$res->error('活跃度参数不正确');
        }

        if (!empty($industry) && !in_array($industry, [1,2,3,4,5,6])) {
            \Cm::$res->error('行业不正确');
        }
        if (!empty($financial_consumption) && !in_array($financial_consumption, [1,2,3,4,5,6,7])) {
            \Cm::$res->error('消费偏好不正确');
        }
        if (!empty($content_style) && !in_array($content_style, [1,2,3,4,5,6])) {
            \Cm::$res->error('内容形式偏好不正确');
        }
        if (!empty($consumption_ability) && !in_array($consumption_ability, [1,2,3,4])) {
            \Cm::$res->error('消费能力不正确');
        }

        $sql = "SELECT c.openid FROM `scrm_weixin_customer` as c ";

        if ($tags) {
            $tagids = str_replace('，', ',',$tags);

            $where = implode(',',  array_map(function ($v){ return "'{$v}'";}, explode(',', $tagids)));
            $sql .= "INNER JOIN `scrm_weixin_customer_label` as l on l.customer_id=c.id AND l.label_id in ($where)";
        }

        $where = " where c.wx_account_id = '{$this->wx_account_id}' ";

        //发送对象
        switch ($to_type) {
            //1：全部粉丝、2：游客、3：潜客:是否是潜客，默认为false:0
            case 2:
                $where .= " and c.is_potential_customer = 0";
                break;
            case 3:
                $where .= " and c.is_potential_customer = 1";
                break;
            default:
                break;
        }

        //关注时间：
        if (is_numeric($subscribe)) {
            $start = null;
            switch ((int)$subscribe) {
                //1：全部时间、2：最近一周、3：最近两周，4：最近一个月
                case 2:
                    $start = date('Y-m-d 00:00:00', strtotime('-7 days'));
                    break;
                case 3:
                    $start = date('Y-m-d 00:00:00', strtotime('-14 days'));
                    break;
                case 4:
                    $start = date('Y-m-d 00:00:00', strtotime('-30 days'));
                    break;
                default:
                    break;
            }
            if ($start) {
                $end = date('Y-m-d H:i:s');
                $where .= " and c.subscribe between '{$start}' and '{$end}'";
            }
        } else {
            list($start, $end) = explode(' ', $subscribe);
            if ($start && $end) {
                $where .= " and c.subscribe between '{$start}' and '{$end}'";
            }
        }

        //年龄标签   年龄标签（1：60后，2：70后，3：80后，4：90后，5：00后，6：未知;默认为6）
        if (!empty($age)) {
            $where .= " and c.age_grade = {$age}";
        }
        if (!empty($sex)) {
            $where .= " and c.sex = {$sex}";
        }
        //教育
        if (!empty($education)) {
            $where .= " and c.education = {$education}";
        }

        if (!empty($territory)) {
            $where .= " and c.territory = {$territory}";
        }
        if (!empty($source)) {
            $source = $source-1;
            if ($source < 0) {
                $source = 0;
            }
            $where .= " and c.subscribe_scene_type = {$source}";
        }
        if (!empty($active_level)) {
            $where .= " and c.active = {$active_level}";
        }
        if (!empty($industry)) {
            $where .= " and c.customer_industry = {$industry}";
        }
        if (!empty($financial_consumption)) {
            $where .= " and c.financial_consumption_preference = {$financial_consumption}";
        }
        if (!empty($content_style)) {
            $where .= " and c.content_style_preference = {$content_style}";
        }
        if (!empty($consumption_ability)) {
            $where .= " and c.consumption_ability = {$consumption_ability}";
        }

        $sql .= $where;

        $customers = Cm::$db->all($sql);

       if (!$customers || count($customers)<=1) {
           Cm::$res->error('未找到满足条件的粉丝');
       }

        $wechat = new wxAction($this->wx_app_id);

        //
        $data= [
            'touser' => $this->_array_column($customers, 'openid')
        ];
//         $data= [
//             'touser' => ['oTVrs0dVYSsogHNPYIr8wdPdY9bQ', 'oTVrs0S2sTg64aQHbc2afKpfd5X0']
//         ];

        if (in_array($type, ['news'])) {
           if (!empty($articles)) {
               $result = (new MaterialModel())->actionArticleAddOther($articles);
               if (!$result) {
                   Cm::$res->error('群发失败');
               }
               $content = $result['media_id'];
           }
        }
        //text：文本
        //、image：素材图片、news：素材图文，template：微信模板、new_graphic：新图文
        switch ($type) {
            //mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
            case 'text':
                $data['msgtype'] = $type;
                $data[$type]['content'] = $content;
                break;
            case 'news':
                //图文消息被判定为转载时，是否继续群发。 1为继续群发（转载），0为停止群发。 该参数默认为0。
                $data['msgtype'] = 'mpnews';
                $data['mpnews']['media_id'] = $content;
                $data['send_ignore_reprint'] = 1;
                break;
        }
        if (isset($data['msgtype']) && !empty($data['msgtype'])) {

            $sendType =[
                1=>'全部粉丝',
                2=>'游客',
                3=>'潜客',
            ];
            //var_dump($data);exit;
            $result = $wechat->sendMassMessage($data);
            if ($result) {
                //发送对象（1：全部粉丝、2：游客、3：潜客）
                $insert = array_filter([
                    'id'=>(new CreateUuid())->toString(),
                    'wx_account_id'=>$this->wx_account_id,
                    'from_user_name'=>$user_name,
                    'to_user_name'=>$to_type,
                    'to_user_name_text'=>$sendType[$to_type],
                    'add_time'=>date('Y-m-d H:i:s'),
                    'msg_type'=>$type,
                    'content'=>$content,
                    'msg_id'=>isset($result['msg_id']) ? $result['msg_id'] : null,
                    'touser'=>implode(',',$data['touser']),
                    'send_ignore_reprint'=>isset($data['send_ignore_reprint']) ? $data['send_ignore_reprint'] : 0,
                    'msg_data_id'=>isset($result['msg_data_id']) ? $result['msg_data_id'].'_1': null,
                    'status'=>1
                ]);

                Cm::$db->insert('scrm_weixin_group_message_log', $insert);
                
                Cm::$res->susess('群发成功！', ['msg_id'=>isset($result['msg_id']) ? $result['msg_id'] : null, 'msg_type'=>$type]);
            } else {
                $insert = array_filter([
                    'id'=>(new CreateUuid())->toString(),
                    'wx_account_id'=>$this->wx_account_id,
                    'from_user_name'=>$user_name,
                    'to_user_name'=>$to_type,
                    'to_user_name_text'=>$sendType[$to_type],
                    'add_time'=>date('Y-m-d H:i:s'),
                    'msg_type'=>$type,
                    'content'=>isset($data[$type]) ? (in_array($type, ['news', 'new_graphic', 'template'])? $data['mpnews']['media_id'] : (in_array($type, ['image']) ? $data[$type]['media_id'] : null)) : null,
                    'msg_id'=>isset($result['msg_id']) ? $result['msg_id'] : 0,
                    'touser'=>implode(',',$data['touser']),
                    'send_ignore_reprint'=>isset($data['send_ignore_reprint']) ? $data['send_ignore_reprint'] : 0,
                    'msg_data_id'=>isset($result['msg_data_id']) ? $result['msg_data_id'].'_1': 0,
                    'status'=>0
                ]);
                Cm::$db->insert('scrm_weixin_group_message_log', $insert);

                Cm::$res->error('群发失败'.(($wechat->errCode=='45065' || $wechat->errCode==45065) ? '此消息已发送，请不要重复发送' : ''));
            }
        } else {
            Cm::$res->error('群发内容不符合微信规则！');
        }
    }


    /**
     * 潜客群发
     */
    public function actionSubmersibleSenMsg()
    {
        $type = Cm::$req->post('type', ['reg'=>'/^\w+/', 'title'=>'发送内容类型']);
        $content= Cm::$req->post('content', [ 'title'=>'发送内容']);
        $user_name= Cm::$req->post('user_name', [ 'title'=>'发送者']);
        $access_connection = (int)Cm::$req->post('access_connection', ['reg'=>'/^\d+/' ,'title'=>'访问连接类型']);
        $title= Cm::$req->post('title', ['title'=>'文章标题']);
        $article_tag= Cm::$req->post('article_tag', ['title'=>'文章标签']);
        $article_type= Cm::$req->post('article_type', ['title'=>'文章类型']);
        $thumb_media_id= Cm::$req->post('thumb_media_id', ['title'=>'封面图片']);
        $author= Cm::$req->post('author', ['title'=>'作者', 'null', 'empty']);
        $digest= Cm::$req->post('digest', ['title'=>'文章摘要', 'null', 'empty']);
        $show_cover_pic= Cm::$req->post('show_cover_pic', ['title'=>'显示封面', 'null', 'empty', 'default'=>0]);
        $url= Cm::$req->post('url', ['title'=>'外部连接地址', 'null', 'empty']);
        $to_type = Cm::$req->post('to_type', ['reg'=>'/^\d+/', 'title'=>'发送对象']);
        $subscribe = Cm::$req->post('subscribe', ['title'=>'关注时间']);
        $age = (int)Cm::$req->post('age', ['reg'=>'/^\d+/', 'title'=>'年龄标签', 'null', 'empty']);
        $sex = (int)Cm::$req->post('sex', ['reg'=>'/^\d+/', 'title'=>'性别', 'null', 'empty']);
        $education = (int)Cm::$req->post('education', ['reg'=>'/^\d+/', 'title'=>'教育标签', 'null', 'empty']);
        $territory = (int)Cm::$req->post('territory', ['reg'=>'/^\d+/', 'title'=>'地域标签', 'null', 'empty']);
        $source = (int)Cm::$req->post('source', ['reg'=>'/^\d+/', 'title'=>'粉丝来源', 'null', 'empty']);
        $active_level = (int)Cm::$req->post('active_level', ['reg'=>'/^\d+/', 'title'=>'活跃度', 'null', 'empty']);
        $industry = (int)Cm::$req->post('industry', ['reg'=>'/^\d+/', 'title'=>'行业标签', 'null', 'empty']);
        $financial_consumption = (int)Cm::$req->post('financial_consumption', ['reg'=>'/^\d+/', 'title'=>'消费偏好标签', 'null', 'empty']);
        $content_style = (int)Cm::$req->post('content_style', ['reg'=>'/^\d+/', 'title'=>'内容形式偏好标签', 'null', 'empty']);
        $consumption_ability = (int)Cm::$req->post('consumption_ability', ['reg'=>'/^\d+/', 'title'=>'消费能力', 'null', 'empty']);
        $tags = Cm::$req->post('tags', ['title'=>'自定义标签', 'null', 'empty']);

        //text
        if (!in_array($type, ['news'])) {
            \Cm::$res->error('群发类型参数不正确');
        }
        if (!in_array($to_type, [1,2,3])) {
            \Cm::$res->error('发送对象参数不正确');
        }

        if (is_numeric($subscribe)) {
            if (!in_array((int)$subscribe, [1,2,3])) {
                \Cm::$res->error('关注时间参数不正确');
            }
        } else {
            if (!preg_match('/^\d{4}-\d{2}-\d{2}\s\d{4}-\d{2}-\d{2}/', $subscribe, $arr)) {
                \Cm::$res->error('关注时间参数不正确');
            }
        }

        if (!in_array($access_connection, [1,2])) {
            \Cm::$res->error('链接类型参数不正确');
        }

        if ($access_connection===1) {
            if (empty($url)) {
                \Cm::$res->error('请输入外部H5链接地址');
            }
        }

        if (!in_array($to_type, [1,2,3])) {
            \Cm::$res->error('发送对象参数不正确');
        }

        if (!empty($age) && !in_array($age, [1,2,3,4,5,6])) {
            \Cm::$res->error('年龄标签参数不正确');
        }

        if (!empty($sex) && !in_array($sex, [1,2])) {
            \Cm::$res->error('性别参数不正确');
        }

        if (!empty($education) && !in_array($education, [1,2,3,4,5,6])) {
            \Cm::$res->error('教育标签参数不正确');
        }

        if (!empty($territory) && !in_array($territory, [1,2,3,4,5,6,7,8])) {
            \Cm::$res->error('地域标签参数不正确');
        }
        if (!empty($source) && !in_array($source, [0,1,2,3,4,5,6,7])) {
            \Cm::$res->error('粉丝来源不正确');
        }
        if (!empty($active_level) && !in_array($active_level, [1,2,3])) {
            \Cm::$res->error('活跃度参数不正确');
        }

        if (!empty($industry) && !in_array($industry, [1,2,3,4,5,6])) {
            \Cm::$res->error('行业不正确');
        }
        if (!empty($financial_consumption) && !in_array($financial_consumption, [1,2,3,4,5,6,7])) {
            \Cm::$res->error('消费偏好不正确');
        }
        if (!empty($content_style) && !in_array($content_style, [1,2,3,4,5,6])) {
            \Cm::$res->error('内容形式偏好不正确');
        }
        if (!empty($consumption_ability) && !in_array($consumption_ability, [1,2,3,4])) {
            \Cm::$res->error('消费能力不正确');
        }

        $sql = "SELECT c.openid FROM `scrm_weixin_customer` as c ";

        if ($tags) {
            $tagids = str_replace('，', ',',$tags);

            $where = implode(',',  array_map(function ($v){ return "'{$v}'";}, explode(',', $tagids)));
            $sql .= "INNER JOIN `scrm_weixin_customer_label` as l on l.customer_id=c.id AND l.label_id in ($where)";
        }

        $where = " where c.wx_account_id = '{$this->wx_account_id}' ";

        //发送对象
        switch ($to_type) {
            //1：全部粉丝、2：游客、3：潜客:是否是潜客，默认为false:0
            case 2:
                $where .= " and c.is_potential_customer = 0";
                break;
            case 3:
                $where .= " and c.is_potential_customer = 1";
                break;
            default:
                break;
        }

        //关注时间：
        if (is_numeric($subscribe)) {
            $start = null;
            switch ((int)$subscribe) {
                //1：全部时间、2：最近一周、3：最近两周，4：最近一个月
                case 2:
                    $start = date('Y-m-d 00:00:00', strtotime('-7 days'));
                    break;
                case 3:
                    $start = date('Y-m-d 00:00:00', strtotime('-14 days'));
                    break;
                case 4:
                    $start = date('Y-m-d 00:00:00', strtotime('-30 days'));
                    break;
                default:
                    break;
            }
            if ($start) {
                $end = date('Y-m-d H:i:s');
                $where .= " and c.subscribe between '{$start}' and '{$end}'";
            }
        } else {
            list($start, $end) = explode(' ', $subscribe);
            if ($start && $end) {
                $where .= " and c.subscribe between '{$start}' and '{$end}'";
            }
        }

        //年龄标签   年龄标签（1：60后，2：70后，3：80后，4：90后，5：00后，6：未知;默认为6）
        if (!empty($age)) {
            $where .= " and c.age_grade = {$age}";
        }
        if (!empty($sex)) {
            $where .= " and c.sex = {$sex}";
        }
        //教育
        if (!empty($education)) {
            $where .= " and c.education = {$education}";
        }

        if (!empty($territory)) {
            $where .= " and c.territory = {$territory}";
        }
        if (!empty($source)) {
            $source = $source-1;
            if ($source < 0) {
                $source = 0;
            }
            $where .= " and c.subscribe_scene_type = {$source}";
        }
        if (!empty($active_level)) {
            $where .= " and c.active = {$active_level}";
        }
        if (!empty($industry)) {
            $where .= " and c.customer_industry = {$industry}";
        }
        if (!empty($financial_consumption)) {
            $where .= " and c.financial_consumption_preference = {$financial_consumption}";
        }
        if (!empty($content_style)) {
            $where .= " and c.content_style_preference = {$content_style}";
        }
        if (!empty($consumption_ability)) {
            $where .= " and c.consumption_ability = {$consumption_ability}";
        }

        $sql .= $where;

        $customers = Cm::$db->all($sql);

       if (!$customers || count($customers)<=1) {
           Cm::$res->error('未找到满足条件的粉丝');
       }

        $wechat = new wxAction($this->wx_app_id);
        //
        $data= [
            'touser' => $this->_array_column($customers, 'openid')
        ];

        // $data= [
        //     'touser' => ['oTVrs0dVYSsogHNPYIr8wdPdY9bQ', 'oTVrs0S2sTg64aQHbc2afKpfd5X0']
        // ];
        $sendType =[
            1=>'全部粉丝',
            2=>'游客',
            3=>'潜客',
        ];

        $wechat = new wxAction($this->wx_app_id);
        $wechatSend = true;
        switch ($type) {
            //mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
            case 'text':
                $data['msgtype'] = $type;
                $data[$type]['content'] = $content;
                break;
            default:
                $imgArtcle = [
                    'title'=>$title,
                    'content'=>$content,
                    'thumb_media_id'=>$thumb_media_id,
                    'digest'=>$digest,
                    'show_cover_pic'=>$show_cover_pic,
                    'content_source_url'=>$access_connection==1  ? $url : '',
                    'author'=>!empty($author) ? $author : $user_name,
                ];
                $result = (new MaterialModel())->actionArticleAddOther(json_encode($imgArtcle));
                if (!$result) {
                    $wechatSend = false;
                    //Cm::$res->error('文章发布到微信失败');
                }
                //图文消息被判定为转载时，是否继续群发。 1为继续群发（转载），0为停止群发。 该参数默认为0。
                $data['msgtype'] = 'mpnews';
                $data['mpnews']['media_id'] = $result['media_id'];
                $data['send_ignore_reprint'] = 1;
                break;
        }
        $article = [
            'id'=>(new CreateUuid())->toString(),
            'title'=>$title,
            'content'=>$content,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s'),
            'created_by'=>0,
            'updated_by'=>0,
            'del_flag'=>0,
            'article_category_id'=>$article_type,
            'article_label_id'=>$article_tag,
            'thumb_media_id'=>$thumb_media_id,
            'media_id'=>isset($result['media_id']) ? $result['media_id'] : '',
            'company_id'=>$this->company_id,
            'wx_account_id'=>$this->wx_account_id,
            'author'=>!empty($author) ? $author : $user_name,
            'digest'=>$digest,
            'show_cover_pic'=>$show_cover_pic,
            'content_source_url'=>$access_connection==1  ? $url : '',
            'to_user_name'=>$to_type,
            'from_user_name'=>$user_name,
            'msg_type'=>$type,
            'touser'=>implode(',', $data['touser']),
            'to_user_name_text'=>$sendType[$to_type],
        ];

        if (!$wechatSend) {
            $article['status']=0;
            //Cm::$db->insert('scrm_weixin_article', $article);
        } else {
            $result = $wechat->sendMassMessage($data);
            if ($result) {
                $article['msg_id']=isset($result['msg_id']) ? $result['msg_id'] : null;
                $article['send_ignore_reprint']=isset($data['send_ignore_reprint']) ? $data['send_ignore_reprint'] : 0;
                $article['msg_data_id']=isset($result['msg_data_id']) ? $result['msg_data_id'].'_1' : 0;
                $article['status']=1;
            }
        }

        Cm::$db->insert('scrm_weixin_article', $article);
        Cm::$res->susess('保存成功、微信发送'.(($wechat->errCode=='45065' || $wechat->errCode==45065) ? '此消息已发送，请不要重复发送' : ($article['status']==1?'成功！':'失败')));
    }
    /**
     * 新建图文图文素材：消息，关键词回复等
     */
    public function actionArticleUpload()
    {
        $articles = Cm::$req->post('articles', ['reg' => '/[^,:{}\\[\\]0-9.\-+Eaeflnr-u \n\r\t]/', 'title' => '图文']);
        $verJson = $this->verJson($articles);
        if (!$verJson['flag']) {
            Cm::$res->error('无效json格式: 无效参数items');
        }

        $arrayDepth = $verJson['dep'];

        $orderRow = $verJson['list'];

        $items = [];
        switch ((int) $arrayDepth) {
            case 1:
                $items[] = [
                    'title' => $orderRow['title'],
                    'thumb_media_id' => $orderRow['thumb_media_id'],
                    'show_cover_pic' => $orderRow['show_cover_pic'],
                    'content' => $orderRow['content'],
                    'content_source_url' => $orderRow['content_source_url'],
                    'author' => $orderRow['author'],
                    'digest' => $orderRow['digest'],
                ];
                break;
            case 2:
                $items = array_map(function ($item) {
                    return [
                        'title' => $item['title'],
                        'thumb_media_id' => $item['thumb_media_id'],
                        'show_cover_pic' => $item['show_cover_pic'],
                        'content' => $item['content'],
                        'content_source_url' => $item['content_source_url'],
                        'author' => $item['author'],
                        'digest' => $item['digest'],
                    ];
                }, $orderRow);
                break;
            default:
                Cm::$res->error('无效json：无效的参数articles');
        }

        if (empty($items)) {
            Cm::$res->error('无效的参数articles');
        }

        $wechat = new wxAction($this->wx_app_id);
        $data = [
            'articles'=>$items
        ];
        $result = $wechat->uploadArticles($data);
        if ($result) {
            foreach ($items as $item) {
                $row = [
                    'id'=>(new CreateUuid())->toString(),
                    'wx_account_id'=>$this->wx_account_id,
                    'title'=>$item['title'],
                    'content'=>$item['content'],
                    'thumb_media_id'=>$item['thumb_media_id'],#临时素材的id
                    'author'=>$item['author'],
                    'content_source_url'=>$item['content_source_url'],
                    'digest'=>$item['digest'],
                    'show_cover_pic'=>$item['show_cover_pic'],
                    'add_time'=>date('Y-m-d H:i:s'),
                    'created_at'=>date('Y-m-d H:i:s', $result['created_at']),
                    //'msgid'=>$item['title'],
                    'media_id'=>$result['media_id'],
                ];

                Cm::$db->insert('scrm_weixin_img_template', $row);
            }

            Cm::$res->susess('success', [
                'media_id'=>$result['media_id'],
            ]);
        } else {
            Cm::$res->error('上传图文消息素材失败');
        }
    }

    /**
     * 删除群发消息
     */
    public function actionSendMsgDel()
    {
        $id = Cm::$req->post('id', ['reg'=>'/[a-zA-Z0-9]+/', 'title'=>'群发记录id']);

        $result = Cm::$db->one("SELECT id, msg_id FROM `scrm_weixin_group_message_log` where id='{$id}' and wx_account_id='{$this->wx_account_id}'");
        if (!$result) {
            Cm::$res->error('群发记录不存在！');
        }

        if (isset($result['msg_id']) && !empty($result['msg_id'])){
            $wechat = new wxAction($this->wx_app_id);
            $wechat->deleteMassMessage($result['msg_id']);
        }

        Cm::$db->delete('scrm_weixin_group_message_log', "id='{$id}' and wx_account_id='{$this->wx_account_id}'");

        Cm::$res->susess('删除成功！');
    }

    /**
     * 删除潜客发布的文章
     */
    public function actionSubmersibleMsgDel()
    {
        $id = Cm::$req->post('id', ['reg'=>'/[a-zA-Z0-9]+/', 'title'=>'潜客文章记录']);

        $result = Cm::$db->one("SELECT id, msg_id,media_id FROM `scrm_weixin_article` where id='{$id}' and wx_account_id='{$this->wx_account_id}'");
        if (!$result) {
            Cm::$res->error('发布文章不存在！');
        }

        $wechat = new wxAction($this->wx_app_id);

        if (isset($result['msg_id']) && !empty($result['msg_id'])){
            $wechat->deleteMassMessage($result['msg_id']);
        }

        if (isset($result['media_id']) && !empty($result['media_id'])){

            $data = Cm::$db->one("SELECT id, media_id,type FROM scrm_weixin_fover_material where media_id='{$result['media_id']}' and wx_account_id='{$this->wx_account_id}'");

            if ($data && $data['type']=='news') {
                Cm::$db->delete('scrm_weixin_fover_material', "id='{$data['id']}'");
                Cm::$db->delete('scrm_weixin_fover_material_items', "material_id='{$data['id']}'");

            }
        }

        Cm::$db->update('scrm_weixin_article',[
            'del_flag'=>0
        ], "id='{$id}' and wx_account_id='{$this->wx_account_id}'");

        Cm::$res->susess('删除成功！');
    }


    /**
     * 发布模板
     */
    public function actionTemplateSend()
    {
        $id = Cm::$req->post('id', ['reg'=>'/[a-zA-Z0-9]+/', 'title'=>'潜客文章记录']);

        $result = Cm::$db->one("SELECT id, title,content,thumb_media_id,author,digest,show_cover_pic,content_source_url,media_id FROM `scrm_weixin_template` where id='{$id}' and wx_account_id='{$this->wx_account_id}'");
        if (!$result) {
            Cm::$res->error('微信模板不存在');
        }

        if (isset($result['media_id']) && !empty($result['media_id'])) {
            Cm::$res->susess('发布成功！');
        }
        $imgArtcle = array_filter( [
            'title'=>$result['title'],
            'content'=>$result['content'],
            'thumb_media_id'=>$result['thumb_media_id'],
            'digest'=>$result['digest'],
            'show_cover_pic'=>$result['show_cover_pic'],
            'content_source_url'=>$result['content_source_url'],
            'author'=>$result['author'],
        ]);
        $data = (new MaterialModel())->actionArticleAddOther(json_encode($imgArtcle));

        if ($data && isset($data['media_id'])) {


            //图文消息被判定为转载时，是否继续群发。 1为继续群发（转载），0为停止群发。 该参数默认为0。
//            $data['msgtype'] = 'mpnews';
//            $data['mpnews']['media_id'] = $result['media_id'];
//            $data['send_ignore_reprint'] = 1;

            $update = array_filter([
                'media_id'=>$data['media_id'],
                'ur'=>$data['url'],
                'thumb_url'=>$data['thumb_url'],
                'material_id'=>$data['material_id'],
            ]);

            //发布到微信：
            Cm::$db->update('scrm_weixin_template', $update, "id='{$result['id']}'");

            $result = $this->sendTemplateNews($data['media_id']);
            if ($result) {
                Cm::$res->susess('发送失败！');
            } else {
                Cm::$res->susess('发送失败！');
            }

        } else {
            Cm::$res->error('发送失败');
        }
    }

    public function sendTemplateNews($media_id)
    {

        $sql = "SELECT c.openid FROM `scrm_weixin_customer` as c ";
        $where = " where c.wx_account_id = '{$this->wx_account_id}' ";
//        $subscribe = 2;
//
//
//        //关注时间：
//        if (is_numeric($subscribe)) {
//            $start = null;
//            switch ((int)$subscribe) {
//                //1：全部时间、2：最近一周、3：最近两周，4：最近一个月
//                case 2:
//                    $start = date('Y-m-d 00:00:00', strtotime('-7 days'));
//                    break;
//                case 3:
//                    $start = date('Y-m-d 00:00:00', strtotime('-14 days'));
//                    break;
//                case 4:
//                    $start = date('Y-m-d 00:00:00', strtotime('-30 days'));
//                    break;
//                default:
//                    break;
//            }
//            if ($start) {
//                $end = date('Y-m-d H:i:s');
//                $where .= " and c.subscribe between '{$start}' and '{$end}'";
//            }
//        } else {
//            list($start, $end) = explode(' ', $subscribe);
//            if ($start && $end) {
//                $where .= " and c.subscribe between '{$start}' and '{$end}'";
//            }
//        }


        $sql .= $where;

        $customers = Cm::$db->all($sql);

        if (!$customers || count($customers)<=1) {
            return false;
        }

        $wechat = new wxAction($this->wx_app_id);
        //
        $data= [
            'touser' => $this->_array_column($customers, 'openid'),
            'msgtype'=>'mpnews',
            'mpnews'=>[
                'mpnews'=>$media_id
            ],
            'send_ignore_reprint'=>1,
        ];

        $result = $wechat->sendMassMessage($data);
        if ($result) {
            //发送对象（1：全部粉丝、2：游客、3：潜客）
            $insert = array_filter([
                'id'=>(new CreateUuid())->toString(),
                'wx_account_id'=>$this->wx_account_id,
                'from_user_name'=>$this->wx_account_id,
                'to_user_name'=>1,
                'to_user_name_text'=>'全部粉丝',
                'add_time'=>date('Y-m-d H:i:s'),
                'msg_type'=>'news',
                'content'=>$media_id,
                'msg_id'=>isset($result['msg_id']) ? $result['msg_id'] : null,
                'touser'=>implode(',',$data['touser']),
                'send_ignore_reprint'=>isset($data['send_ignore_reprint']) ? $data['send_ignore_reprint'] : 0,
                'msg_data_id'=>isset($result['msg_data_id']) ? $result['msg_data_id'].'_1': 0,
                'status'=>1
            ]);
            Cm::$db->insert('scrm_weixin_template_send_log', $insert);

            return true;
        } else {

            return false;
        }
    }
    /**
     * 判断json是否符合标准
     * @param $items
     * @return array
     */
    private function verJson($items, $flag = false)
    {
        $itemsArray = json_decode($items, true);

        $arrayDepth = 1;
        $errorJson = true;
        if ($itemsArray) {
            $arrayDepth = self::array_depth($itemsArray);
            if ($arrayDepth > 1) {
                foreach ($itemsArray as $row) {
                    $key = array_keys($row);
                    if (!empty($key) && is_array($key)) {

                        if (!in_array('title', $key)) {
                            $errorJson = false;
                        }

                        if (!in_array('thumb_media_id', $key)) {
                            $errorJson = false;
                        }

                        if (!in_array('show_cover_pic', $key)) {
                            $errorJson = false;
                        }

                        if (!in_array('content', $key)) {
                            $errorJson = false;
                        }
                        if (!in_array('content_source_url', $key)) {
                            $errorJson = false;
                        }
                        if (!in_array('author', $key)) {
                            $errorJson = false;
                        }
                        if (!in_array('digest', $key)) {
                            $errorJson = false;
                        }
                        // if ($flag && !in_array('id', $key)) {
                        //     $errorJson=false;
                        // }

                    } else {
                        $errorJson = false;
                    }

                }
            } else {
                $key = array_keys($itemsArray);
                if (!empty($key) && is_array($key)) {

                    if (!in_array('title', $key)) {
                        $errorJson = false;
                    }

                    if (!in_array('thumb_media_id', $key)) {
                        $errorJson = false;
                    }

                    if (!in_array('show_cover_pic', $key)) {
                        $errorJson = false;
                    }

                    if (!in_array('content', $key)) {
                        $errorJson = false;
                    }
                    if (!in_array('content_source_url', $key)) {
                        $errorJson = false;
                    }
                    if (!in_array('author', $key)) {
                        $errorJson = false;
                    }
                    if (!in_array('digest', $key)) {
                        $errorJson = false;
                    }

                } else {
                    $errorJson = false;
                }
            }
        } else {
            $errorJson = false;
        }

        return [
            'flag' => $errorJson,
            'dep' => $arrayDepth,
            'list' => $itemsArray,
        ];
    }
}